/**
 *
 * @description 登录、获取用户信息、退出登录、清除accessToken逻辑，不建议修改
 */

import Vue from 'vue'
import { login, logout, getUserInfo } from '@/api/auth'
import { getAccessToken, removeAccessToken, setAccessToken } from '@/utils/accessToken'
import { resetRouter } from '@/router'
import { title } from '@/config'

const state = () => ({
  accessToken: getAccessToken(),
  account: '',
  userId: '',
  userName: '',
  userCode: '',
  permissions: [],
  roles: [],
})
const getters = {
  accessToken: (state) => state.accessToken,
  userName: (state) => state.userName,
  userCode: (state) => state.userCode,
  userId: (state) => state.userId,
  account: (state) => state.account,
  permissions: (state) => state.permissions,
  roles: (state) => state.roles,
}
const mutations = {
  setAccessToken(state, accessToken) {
    state.accessToken = accessToken
    setAccessToken(accessToken)
  },
  setAccount(state, account) {
    state.account = account
  },
  setUserName(state, userName) {
    state.userName = userName
  },
  setUserCode(state, userCode) {
    state.userCode = userCode
  },
  setUserId(state, userId) {
    state.userId = userId
  },
  setPermissions(state, permissions) {
    state.permissions = permissions
  },
  setRoles(state, roles) {
    state.roles = roles
  },
}
const actions = {
  setPermissions({ commit }, permissions) {
    commit('setPermissions', permissions)
  },
  async login({ commit }, userInfo) {
    const { data } = await login(userInfo)

    const accessToken = data
    if (accessToken) {
      commit('setAccessToken', accessToken)
      const hour = new Date().getHours()
      const thisTime = hour < 8 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 18 ? '下午好' : '晚上好'
      Vue.prototype.$baseNotify(`欢迎登录${title}`, `${thisTime}！`)
    } else {
      Vue.prototype.$baseMessage(`登录接口异常，未正确返回${tokenName}...`, 'error')
    }
  },
  async getUserInfo({ commit, state }) {
    const { data } = await getUserInfo()
    if (!data) {
      Vue.prototype.$baseMessage('验证失败，请重新登录...', 'error')
      return false
    }
    let { permissions, roles, account, userId, userCode, userName } = data
    if (permissions && account && Array.isArray(permissions)) {
      commit('setPermissions', permissions)
      commit('setRoles', roles)
      commit('setAccount', account)
      commit('setUserName', userName)
      commit('setUserCode', userCode)
      commit('setUserId', userId)
      return permissions
    } else {
      Vue.prototype.$baseMessage('用户信息接口异常', 'error')
      return false
    }
  },
  async logout({ dispatch }) {
    await logout()
    await dispatch('resetAccessToken')
    await resetRouter()
    location.reload()
  },
  resetAccessToken({ commit }) {
    commit('setPermissions', [])
    commit('setAccessToken', '')
    removeAccessToken()
  },
}
export default {
  state,
  getters,
  mutations,
  actions,
}
